﻿var http=require("http");
var fs=require("fs");
var url=require("url");

//创建服务器
http.createServer(function(req,resp){
	
	//解析请求，包括文件名
	var pathname=url.parse(req.url).pathname;
	
	//输出请求的文件名
	console.log("Request for "+pathname+" received.");
	
	console.log(pathname.substr(1));
	//从文件系统中读取请求的文件内容
	fs.readFile(pathname.substr(1),function(err,data){
		if(err){
			console.log(err);
			//Http状态码：404：Not Found
			//Content Type：text/plain
			resp.writeHead(404,{'Content-Type':'text/html;charset=utf8'});
		}else{
			//http状态码：200：ok
			//content type：text/plain
			resp.writeHead(200,{'Content-Type':'text/html;charset=utf8'});
			//响应文件内容
			resp.write(data.toString());
		}
		
		//发送响应数据
		resp.end();
	});
	
}).listen(8081);

console.log("Server running at http://127.0.0.1:8081/");